package com.apes.pi.parser;


import com.apes.framework.api.ApesParser;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.EsbRouter;
import com.apes.framework.plugin.esb.processor.ChainProcessor;
import com.apes.framework.plugin.esb.processor.ConsumerProcessor;
import com.apes.framework.plugin.filereader.xml.ApesElement;
import com.apes.framework.plugin.filereader.xml.SimpleApesElement;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.EventUtil;
import com.apes.oap.event.AfterStartedRopEvent;
import com.apes.oap.event.RopEventListener;
import com.apes.pi.model.QueueReceiver;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

/**
 * 功能：PiEventListener RopListener
 *
 * @author xul
 * @create 2019-11-09 14:05
 */
@Component
public class PiEventListener implements RopEventListener<AfterStartedRopEvent> {
    protected final Logger logger = LogManager.getLogger(PiEventListener.class);

    @Autowired
    private QueueParser queueParser;

    public void onRopEvent(AfterStartedRopEvent ropRopEvent) {
        QueueCacheManager queueCacheManager = SpringManager.getBean(QueueCacheManager.class);
        queueCacheManager.getQueueReceivers().forEach((k, v) -> {
            subscribe(v);
        });
        queueCacheManager.getQueues().forEach((k, v) -> {
            EsbRouter.setRouter(v.methodName(), ApesConst.METHOD_VERSION, new PiQueueElement(v));
        });
    }

    public void subscribe(QueueReceiver v) {
        /**传输模式（0:同步，1:异步）**/
        if (v.getQueue().getType() == 0) return;
        ApesElement element = new SimpleApesElement();
        element.setAttribute("topic", v.topicName());
        element.setAttribute("isTransaction", "false");
        element.setAttribute("isBackup", "true");
        element.setAttribute("period", "5");
        element.setParser((ApesParser<SimpleApesElement, ChainProcessor>) apesElement -> {
            ConsumerProcessor processor = new ConsumerProcessor();
            queueParser.setQueueReceiverProcessor(processor, v);
            queueParser.setPipeProcessor(processor, v.getQueue().getId(), "after", "QueueReceiver", new HashMap<>());
            return processor;
        });
        EventUtil.sendAynEvent(this, "event:mq.subscribe", element);
    }


    public int getOrder() {
        return 120;
    }
}

